Page({
  data: {
    orderInfo: {},
    refreshTimer: null,
    refreshInterval: 15000, // 15秒刷新一次
    isLoading: false,
    statusMap: {
      '待支付': { color: '#FF5722', icon: 'clock-o' },
      '待发货': { color: '#FFB800', icon: 'truck' },
      '已发货': { color: '#1E9FFF', icon: 'paper-plane-o' },
      '已完成': { color: '#009688', icon: 'check-circle-o' },
      '已评价': { color: '#87CEEB', icon: 'comment-o' },
      '售后中': { color: '#FF4500', icon: 'wrench' }
    }
  },

  onLoad(options) {
    let orderInfo = null;
    
    // 从URL参数获取订单信息
    if (options.orderInfo) {
      try {
        orderInfo = JSON.parse(decodeURIComponent(options.orderInfo));
      } catch (error) {
        console.error('解析订单信息失败:', error);
        wx.showToast({ title: '订单信息获取失败', icon: 'none' });
        setTimeout(() => wx.navigateBack(), 1500);
        return;
      }
    }
    
    if (orderInfo) {
      this.setData({ orderInfo }, () => {
        this.startAutoRefresh();
        this.showOrderStatusAnimation();
      });
    } else {
      wx.showToast({ title: '订单信息获取失败', icon: 'none' });
      setTimeout(() => wx.navigateBack(), 1500);
    }
  },

  onUnload() {
    this.stopAutoRefresh();
  },

  // 启动自动刷新
  startAutoRefresh() {
    this.stopAutoRefresh();
    this.data.refreshTimer = setInterval(() => {
      this.fetchOrderDetail();
    }, this.data.refreshInterval);
  },

  // 停止自动刷新
  stopAutoRefresh() {
    if (this.data.refreshTimer) {
      clearInterval(this.data.refreshTimer);
      this.data.refreshTimer = null;
    }
  },

  // 获取最新订单详情
  fetchOrderDetail() {
    const { orderInfo } = this.data;
    if (!orderInfo.orderNumber) return;
    
    // 显示加载状态
    this.setData({ isLoading: true });
    
    // 模拟从服务器获取订单详情
    setTimeout(() => {
      const remoteOrders = wx.getStorageSync('paidOrders') || [];
      const updatedOrder = remoteOrders.find(order => order.orderNumber === orderInfo.orderNumber);
      
      if (updatedOrder) {
        // 检查订单状态是否有变化
        const statusChanged = updatedOrder.orderStatus !== orderInfo.orderStatus;
        
        this.setData({ 
          orderInfo: updatedOrder,
          isLoading: false
        });
        
        // 如果状态有变化，显示提示并播放动画
        if (statusChanged) {
          wx.showToast({ 
            title: `订单状态已更新为${updatedOrder.orderStatus}`, 
            icon: 'success',
            duration: 1500
          });
          this.showOrderStatusAnimation();
        }
      } else {
        this.setData({ isLoading: false });
      }
    }, 800);
  },

  // 显示订单状态变化动画
  showOrderStatusAnimation() {
    const animation = wx.createAnimation({
      duration: 800,
      timingFunction: 'ease-out'
    });
    
    animation.scale(1.2).opacity(0.8).step();
    animation.scale(1).opacity(1).step();
    
    this.setData({
      statusAnimation: animation.export()
    });
  },

  // 查看物流轨迹
  handleViewTracking() {
    const trackingNumber = this.data.orderInfo.logisticsInfo?.trackingNumber;
    const logisticsCompany = this.data.orderInfo.logisticsInfo?.company || '默认物流';
    
    if (!trackingNumber) {
      wx.showToast({ title: '暂无物流信息', icon: 'none' });
      return;
    }
    
    wx.showLoading({ title: '查询物流中...' });
    
    // 模拟物流查询
    setTimeout(() => {
      wx.hideLoading();
      wx.showModal({
        title: `${logisticsCompany}物流信息`,
        content: `物流单号: ${trackingNumber}\n\n物流状态: ${this.data.orderInfo.logisticsInfo.status}\n\n最新更新: 2023-06-12 14:30:00\n\n配送中，预计明天送达`,
        showCancel: false,
        confirmText: '返回',
        confirmColor: '#9E1310'
      });
    }, 1000);
  },

  // 支付订单
  handlePayment() {
    const { orderInfo } = this.data;
    if (orderInfo.orderStatus !== '待支付') {
      wx.showToast({ title: '当前订单无需支付', icon: 'none' });
      return;
    }
    
    wx.showModal({ 
      title: '确认支付', 
      content: `确定要支付该订单吗？\n金额: ¥${orderInfo.paymentInfo.actualPayment}`, 
      confirmColor: '#9E1310',
      success: (res) => { 
        if (res.confirm) { 
          wx.showLoading({ title: '支付处理中...' });
          
          // 模拟支付处理
          setTimeout(() => {
            const isSuccess = Math.random() > 0.2; // 80%成功率
            
            if (isSuccess) { 
              // 支付成功，更新订单状态
              let updatedOrder = { ...orderInfo };
              updatedOrder.orderStatus = '待发货';
              
              // 更新本地存储
              const orders = wx.getStorageSync('paidOrders') || [];
              const newOrders = orders.map(order => 
                order.orderNumber === updatedOrder.orderNumber ? updatedOrder : order
              );
              wx.setStorageSync('paidOrders', newOrders);
              
              // 跳转到支付成功页
              wx.hideLoading();
              const encodedOrderInfo = encodeURIComponent(JSON.stringify(updatedOrder));
              wx.navigateTo({ 
                url: `/pages/PaySuccess/PaySuccess?orderInfo=${encodedOrderInfo}` 
              });
            } else { 
              // 支付失败
              wx.hideLoading();
              wx.showToast({ 
                title: '支付失败，请重试', 
                icon: 'none',
                duration: 2000
              });
            } 
          }, 2000);
        } 
      } 
    }); 
  },

  // 取消订单
  handleCancelOrder() {
    const { orderInfo } = this.data;
    
    // 检查是否可以取消订单
    if (orderInfo.orderStatus === '已完成' || orderInfo.orderStatus === '已评价') {
      wx.showToast({ title: '已完成的订单无法取消', icon: 'none' });
      return;
    }
    
    wx.showModal({
      title: '确认取消订单',
      content: '确定要取消该订单吗？取消后将无法恢复。',
      confirmColor: '#9E1310',
      success: (res) => {
        if (res.confirm) {
          wx.showLoading({ title: '取消订单中...' });
          
          // 模拟取消订单处理
          setTimeout(() => {
            // 更新订单状态为已取消
            let updatedOrder = { ...orderInfo };
            updatedOrder.orderStatus = '已取消';
            
            // 更新本地存储
            const orders = wx.getStorageSync('paidOrders') || [];
            const newOrders = orders.map(order => 
              order.orderNumber === updatedOrder.orderNumber ? updatedOrder : order
            );
            wx.setStorageSync('paidOrders', newOrders);
            
            wx.hideLoading();
            wx.showToast({ 
              title: '订单已取消', 
              icon: 'success',
              duration: 1500
            });
            
            // 返回订单列表页
            setTimeout(() => {
              wx.navigateBack();
            }, 1500);
          }, 1500);
        }
      }
    });
  },

  // 确认收货
  handleConfirmReceipt() {
    const { orderInfo } = this.data;
    if (orderInfo.orderStatus !== '已发货') {
      wx.showToast({ title: '当前状态无法确认收货', icon: 'none' });
      return;
    }
    
    wx.showModal({
      title: '确认收货',
      content: '确定已收到商品并确认收货吗？',
      confirmColor: '#9E1310',
      success: (res) => {
        if (res.confirm) {
          wx.showLoading({ title: '处理中...' });
          
          // 模拟确认收货处理
          setTimeout(() => {
            // 更新订单状态
            let updatedOrder = { ...orderInfo };
            updatedOrder.orderStatus = '已完成';
            updatedOrder.logisticsInfo.status = '已完成';
            
            // 更新本地存储
            const orders = wx.getStorageSync('paidOrders') || [];
            const newOrders = orders.map(order => 
              order.orderNumber === updatedOrder.orderNumber ? updatedOrder : order
            );
            wx.setStorageSync('paidOrders', newOrders);
            
            wx.hideLoading();
            wx.showToast({ 
              title: '确认收货成功', 
              icon: 'success',
              duration: 1500
            });
            
            // 更新当前页面数据
            this.setData({ orderInfo: updatedOrder });
          }, 1000);
        }
      }
    });
  },

  // 申请售后
  handleAfterSale() {
    const { orderInfo } = this.data;
    if (orderInfo.orderStatus !== '已完成' && orderInfo.orderStatus !== '已评价') {
      wx.showToast({ title: '当前状态无法申请售后', icon: 'none' });
      return;
    }
    
    wx.navigateTo({
      url: `/pages/AfterSale/AfterSale?orderInfo=${encodeURIComponent(JSON.stringify(orderInfo))}`
    });
  },

  // 评价订单
  handleEvaluate() {
    const { orderInfo } = this.data;
    if (orderInfo.orderStatus !== '已完成') {
      wx.showToast({ title: '当前状态无法评价', icon: 'none' });
      return;
    }
    
    wx.navigateTo({
      url: `/pages/Evaluate/Evaluate?orderInfo=${encodeURIComponent(JSON.stringify(orderInfo))}`
    });
  },

  // 联系客服
  handleContactCustomerService() {
    wx.showModal({
      title: '联系客服',
      content: '客服电话：400-123-4567\n工作时间：9:00-22:00',
      cancelText: '返回',
      confirmText: '立即拨打',
      confirmColor: '#9E1310',
      success: (res) => {
        if (res.confirm) {
          wx.makePhoneCall({
            phoneNumber: '4001234567'
          });
        }
      }
    });
  }
});
